'use strict';

const Service = require('egg').Service;
const util = require('../util/util.js');


class OrderService extends Service {
  async createOrder(rid,tid,dids,total,openId) {
    try{
        const code = util.createCode();
        const order = await this.app.mysql.insert('orders',{
            billcode:code,
            total:total,
        });

        if(order.affectedRows === 1){
            const orderdish = await this.app.mysql.insert('order_dishes',{
                oid:code,
                dids:JSON.stringify(dids)
            });
            const tableorder = await this.app.mysql.insert('table_order',{
                tid:tid,
                oid:code
            });
            const customerorder = await this.app.mysql.insert('customer_order',{
                cid:openId,
                oid:code
            });
            const orderrest = await this.app.mysql.insert('order_restaurant',{
                rid:rid,
                oid:code
            });
            if(orderdish.affectedRows === 1 && tableorder.affectedRows === 1
                 && customerorder.affectedRows === 1 && orderrest.affectedRows === 1){
                const tablestatus = await this.app.mysql.query('UPDATE tablez SET `using` = 1 WHERE `code` = ?',[code])
                if(tablestatus.affectedRows === 1){
                    return code
                }else{
                    return 'error'
                }
            }else{
                return 'error'
            }
        }else{
            return 'error'
        }
    }catch(err){
        return 'error'
    }
  }

  async orderRecord(openid,paystatus){
      try{
          const result = await this.app.mysql.query('SELECT orders.* FROM\
                customer_order INNER JOIN orders\
                ON customer_order.oid = orders.billcode\
                WHERE customer_order.cid = ? \
                AND orders.paystatus = ?',[openid,paystatus]);

          if(result){
              return result;
          }else{
              return 'error';
          }
      }catch(err){
          return 'error';
      }
  }

  async recordDetail(billcode){
      try{
        var dids = await this.app.mysql.query('SELECT dids FROM order_dishes WHERE oid = ?',billcode);
        var dishes = await this.app.mysql.query('select * from dish where id IN (?)',[JSON.parse(dids[0].dids)]);

        return dishes;
      }catch(err){
          return 'error';
      }
  }
}

module.exports = OrderService;
